<template>
  <view class="pay-list">
    <uni-list>
      <uni-list-item
        thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
        thumb-size="min"
        title="楼栋"
        @click="buildingClick"
        link
        :rightText="building"
      />
      <uni-list-item
        thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
        thumb-size="min"
        title="楼层"
        @click="floorClick"
        link
        :rightText="floor"
      />
      <uni-list-item
        thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
        thumb-size="min"
        title="户号"
        @click="accountClick"
        link
        :rightText="account"
      />
    </uni-list>
    <view class="card_box">
      <historicalArrears
        v-for="item in infoData"
        :key="item.id"
        :infoData="item"
        :activeId="order"
        @on-change="headelChange"
      >
      </historicalArrears>
      <view class="expiration_box" v-if="expiration !== ''">
        <view class="expiration_text" v-if="!isNotADate(expiration)">
          还未到最新缴费时间，下次缴费时间为{{
            expiration
          }}，请于缴费时间再来缴费</view
        >
        <view class="expiration_text" v-else> {{ expiration }}</view>
      </view>
    </view>
    <none-data
      v-if="
        infoData.length === 0 && expiration == '' && account !== '请选择户号'
      "
    />
    <up-picker
      :show="buildingShow"
      @confirm="headelBuildingSaveClick"
      @cancel="buildingShow = false"
      :columns="buildingList"
      keyName="name"
    ></up-picker>
    <up-picker
      :show="floorShow"
      @confirm="headelFloorSaveClick"
      @cancel="floorShow = false"
      :columns="floorList"
      keyName="name"
    ></up-picker>
    <up-picker
      :show="accountShow"
      @confirm="headelAccountSaveClick"
      @cancel="accountShow = false"
      :columns="accountList"
      keyName="name"
    ></up-picker>
    <up-modal
      :show="pattern"
      @confirm="payBroadbandOrder"
      @cancel="pattern = false"
      ref="uModal"
      :showCancelButton="true"
      :asyncClose="true"
    >
      <view class="box">
        <view class="title"> 缴费确认 </view>
        <view class="content_box">
			<view class="i">户号：{{parseInt(building)}}-{{account}}</view>
			<view class="i">缴费类别：宽带缴费</view>
			<view class="i">缴费金额：{{ payAmount }}</view>
        </view>
      </view>
    </up-modal>
    <view class="room-btn broadband">
      <button
        class="btn lose"
        v-if="
          account == '请选择户号' ||
          (expiration !== '' && account !== '请选择户号')
        "
        @click="loseClick"
      >
        确认缴费
      </button>
      <button class="btn" v-else @click="validateChange">确认缴费</button>
      <!-- <button class="btn" v-if="indicate" @click="jump">确认缴费</button> -->
    </view>
  </view>
</template>

<script setup>
import {
  getBroadbandCorporateListApi,
  getBroadbandCorporateOrderApi,
  getFloorListApi,
  getBroadbandOnLineApi,
} from "@/package_property/pages/api/broadband.js";
import { getDictConfigListByType } from "@/package_property/pages/api/home.js";
import { payBroadbandOrderApi } from "@/package_property/pages/api/my.js";
import UniListItem from "@/uni_modules/uni-list/components/uni-list-item/uni-list-item.vue";
import UniList from "@/uni_modules/uni-list/components/uni-list/uni-list.vue";
import historicalArrears from "@/package_property/pages/components/historical-arrears/index.vue";
import { ref } from "vue";
import { customNav } from "../../../utils/customNav";
import { onLoad, onShow } from "@dcloudio/uni-app";
const order = ref("");
const orderData = ref({});
const building = ref("请选择楼栋");
const buildingId = ref("");
const floor = ref("请选择楼层");
const account = ref("请选择户号");
const monthly = ref("");
const expiration = ref("");
const indicate = ref(false);
const buildingShow = ref(false);
const floorShow = ref(false);
const accountShow = ref(false);
const pattern = ref(false);
const payAmount = ref(0)
const pageData = ref({
  page: 1,
  size: 10,
});
const buildingList = ref([
  [
    {
      name: "1单元",
      id: "1",
    },
    {
      name: "2单元",
      id: "2",
    },
  ],
]);
const floorList = ref([[]]);
const accountList = ref([[]]);
const infoData = ref([]);

let installedNouse = ref(true)

function buildingClick() {
  buildingShow.value = true;
}
function floorClick() {
  if (floorList.value[0].length !== 0) {
    floorShow.value = true;
  } else {
    uni.showToast({ title: "请选择楼栋", duration: 2000, icon: "none" });
  }
}
function accountClick() {
  if (accountList.value[0].length !== 0) {
    accountShow.value = true;
  } else {
    uni.showToast({ title: "请选择楼层", duration: 2000, icon: "none" });
  }
}

function headelBuildingSaveClick(n) {
  building.value = n.value[0].name;
  buildingId.value = n.value[0].id;
  buildingShow.value = false;
  getFloorListData();
}
function headelFloorSaveClick(n) {
  floor.value = n.value[0].name;
  floorShow.value = false;
  getBroadbandCorporateList();
}
function headelAccountSaveClick(n) {
  console.log("change", n);
  account.value = n.value[0].name;
  accountShow.value = false;
  getBroadbandOnLine();
}
function headelChange(data) {
  console.log("组件参数", data);
  order.value = data?.id;
  orderData.value = data;
  if (data?.id) {
	  payAmount.value = data.payable
  } else {
	  payAmount.value = 0
  }
}

function validateChange() {
  if (account.value !== "请选择户号") {
    let num = infoData.value.filter((item) => item.userPayStatus == "0").length;
    if (infoData.value.length !== 0) {
      console.log("num", num);
      console.log("order.value", order.value);

      if (num !== 0 && order.value !== "" && order.value !== undefined) {
        if (order.value !== "" && !indicate.value) {
          pattern.value = true;
        }
      } else {
        uni.showToast({
          title: "请先选择结算历史欠费订单",
          duration: 2000,
          icon: "none",
        });
      }
    } else {
      jump();
    }
  } else {
    uni.showToast({ title: "请选择户号", duration: 2000, icon: "none" });
  }
}
async function getFloorListData() {
  let res = await getFloorListApi(buildingId.value);
  const { code, data } = res || {};
  if (code == 200) {
    console.log("getFloorListApi", data);
    floorList.value[0] = data.map((o) => {
      return {
        name: o,
      };
    });
  }
}
async function getBroadbandCorporateList() {
  let res = await getBroadbandCorporateListApi({
    unit: buildingId.value,
    floor: floor.value,
  });
  const { code, data } = res || {};
  if (code == 200) {
    console.log("getBroadbandCorporateListApi", data);
    accountList.value[0] = data.map((o) => {
      return {
        name: o.accountNumber,
      };
    });
  }
}
async function getBroadbandCorporateOrder() {
  let res = await getBroadbandCorporateOrderApi({
    page: pageData.value.page,
    size: pageData.value.size,
    accountNumber: account.value,
  });
  const { code, data } = res || {};
  if (code === 200) {
    console.log("getBroadbandCorporateOrderApi", data);

    let info = data.records.filter(item => item.id !== orderIdHide.value).map((o) => {
      return {
        id: o.id,
        cycle: o.arrearsMonth,
        monthly: monthly.value,
        payable: o.meetMoney,
        followUp: o.updateTime,
        notes: o.notes,
        payWay: o.payWay,
        userPayStatus: o.userPayStatus,
        account:`${parseInt(building.value)}-${account.value}`
      }

    });
    console.log("getBroadbandCorporateOrderApi-records", info);

    if (pageData.value.page !== 1) {
      infoData.value = infoData.value.concat(info);
    } else {
      infoData.value = info;
    }
  }
}
// 宽带月租
async function getBroadbandMonthlyRent() {
  const res = await getDictConfigListByType("1830864481711304706");
  const { code, data } = res || {};
  if (code == 200) {
    monthly.value = Number(data[0].children[0].filedName);
  }
}

let orderIdHide = ref('')
async function payBroadbandOrder() {
  let type = {
    orderId: order.value,
    // #ifdef MP-WEIXIN
    payType: "0",
    // #endif
    // #ifndef MP-WEIXIN
    payType: "1",
    // #endif
  };
  console.log(type);

  const res = await payBroadbandOrderApi(type);
  const { code, data } = res || {};
  if (code == 200) {
    orderIdHide.value = order.value

    // console.log("data",data);
    // #ifdef MP-WEIXIN
    weixinClick(data);
    // #endif
    // #ifndef MP-WEIXIN
    weChatAppPay(data);
    // #endif
  }
}
/**
 * 唤起支付
 * @param payData
 */
const weixinClick = (payData) => {
  uni.requestPayment({
    provider: "wxpay",
    timeStamp: payData.timeStamp,
    nonceStr: payData.nonceStr,
    package: payData.prepayId,
    signType: payData.signType,
    paySign: payData.paySign,
    success: function (res) {
      console.log("success:" + JSON.stringify(res));
      uni.showToast({
        title: "支付成功",
        duration: 2000,
        success: () => {
          pattern.value = false;
          pageData.value.page = 1;
          getBroadbandOnLine();
        },
      });
    },
    fail: function (err) {
      orderIdHide.value = ''
      order.value = ''
      pattern.value = false;
      if (err.errMsg == "requestPayment:fail cancel")
        return uni.showToast({
          title: "您已取消支付",
          duration: 2000,
          icon: "none",
        });
      uni.showToast({ title: "支付失败", duration: 2000, icon: "none" });
      console.log("fail:" + JSON.stringify(err));
    },
  });
};

// 微信APP支付
const weChatAppPay = (payData) => {
  let params = {
    partnerId: payData.partnerId, //商户号
    prepayId: payData.prepayId, //预支付交易会话ID
    nonceStr: payData.nonceStr, //随机字符串
    timeStamp: payData.timeStamp, //时间戳
    sign: payData.paySign, //签名
  };
  window.mobile.jsCallPayWx(JSON.stringify(params));
};
async function getBroadbandOnLine() {
  expiration.value = "";
  infoData.value = [];
  const res = await getBroadbandOnLineApi({
    accountNumber: account.value,
  });
  const { code, data } = res || {};
  if (code == 200) {
    console.log("getBroadbandOnLineApi", data);
    switch (data) {
      case "新的订单已产出":
        getBroadbandCorporateOrder();
        installedNouse.value = false;
        break;
      case "房间宽带已安装未使用":
        indicate.value = true;
        installedNouse.value = true;
        expiration.value = data;
        break;
      default:
        expiration.value = data;
        break;
    }
  }
}
function jump() {
  customNav(`pay-details?room=${account.value}&down=${indicate.value}`);
}
function loseClick() {
  if (account.value == "请选择户号") {
    uni.showToast({ title: "请选择户号", duration: 2000, icon: "none" });
  } else if (!isNotADate(expiration.value)) {
    uni.showToast({
      title: "请等到下次缴费日期时，再来进行缴费",
      duration: 2000,
      icon: "none",
    });
  } else {
    uni.showToast({ title: expiration.value, duration: 2000, icon: "none" });
  }
}
function isNotADate(value) {
  const date = new Date(value);
  return isNaN(date.getTime());
}
onLoad(() => {
  getBroadbandMonthlyRent();
});
onShow(() => {
  if (account.value !== "请选择户号") {
    getBroadbandOnLine();
  }
});
</script>

<style lang="less">
.card_box {
  width: 100vw;
  display: flex;
  flex-flow: column nowrap;
  align-items: center;
  padding: 20rpx 0;
  max-height: 73vh;
  overflow-y: scroll;
  .expiration_box {
    width: 100%;
    height: 200rpx;
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    margin-top: 30rpx;
    .expiration_text {
      width: 70%;
      text-align: center;
    }
  }
}
.box {
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
  .title {
    width: 100%;
    font-size: @font-size-39;
    text-align: center;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
  .room {
    font-size: @font-size-39;
    font-weight: bold;
    color: @color-red;
  }
}
</style>